package cn.kjcoder.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kjcoder.springcloud.service.IPaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2021/12/24
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Service
public class PaymentServiceImpl implements IPaymentService {

    /*****************************************服务降级***************************************************/

    //成功
    public String payment_OK(Integer id){
        return "线程池：" + Thread.currentThread().getName() + " payment_OK,id=" + id + "\t" + "嘻嘻";
    }

    //设置自身调用超时时间的峰值，峰值内可以正常运行，超过了需要有兜底的方法进行处理，作服务降级fallback操作
    //3秒内正常执行业务操作，超过3秒调用降级方法，执行兜底方法
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String payment_Timeout(Integer id){
        //模拟复杂的业务需要耗费的时间
        int timeNum = 3;
        //int age = 10 / 0;
        try { TimeUnit.SECONDS.sleep(timeNum); }catch (Exception e) {e.printStackTrace();}
        return "线程池：" + Thread.currentThread().getName() + " payment_Timeout,id = " + id + "\t" + "啊啊啊" + "耗时：" + timeNum + " 秒";
    }
    //兜底方法
    public String paymentInfo_TimeoutHandler(Integer id){
        return  "系统繁忙，或者出现错误，请稍后重试";
    }


    /*****************************************服务熔断***************************************************/

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围10s
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("*****id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功,流水号："+serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " +id;
    }



}
